using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using Microsoft.SqlServer.Dts.Runtime;

namespace SSIS.Tasks
{
    public partial class ExecPackageTaskUIForm : Form
    {
        private TaskHost _taskHost;
        private Connections _connections;
        private Package targetPackage;
        private mappingCollection mappings;

        public ExecPackageTaskUIForm()
        {
            InitializeComponent();
        }

        public ExecPackageTaskUIForm(TaskHost taskHost, Connections connections)
        {
            InitializeComponent();
            _taskHost = taskHost;
            _connections = connections;
            if (_taskHost != null)
            {
                pkgLocationCombo.Text = "File System";
                if ((this._taskHost.Properties["PackagePath"].GetValue(_taskHost) != null)&&(this._taskHost.Properties["PackagePath"].GetValue(_taskHost).ToString() != string.Empty))
                {
                    pkgLocationCombo.Text = this._taskHost.Properties["PackageLocation"].GetValue(_taskHost).ToString();
                    txtPkgPath.Text = this._taskHost.Properties["PackagePath"].GetValue(_taskHost).ToString();
                    
                    Microsoft.SqlServer.Dts.Runtime.Application app = new Microsoft.SqlServer.Dts.Runtime.Application();

                    if (pkgLocationCombo.Text.CompareTo("File System") == 0)
                    {
                       targetPackage = app.LoadPackage(this._taskHost.Properties["PackagePath"].GetValue(_taskHost).ToString(), null);
                    }
                    else
                    {
                       string serverName = txtPkgPath.Text.Substring(0, txtPkgPath.Text.IndexOf("\\"));
                       string packageName = "MSDB\\" + txtPkgPath.Text.Substring(serverName.Length + 1);
                       targetPackage = app.LoadFromDtsServer(packageName, serverName, null);
                    }

                    //Load Mappings
                    mappings = (mappingCollection)_taskHost.Properties["Mappings"].GetValue(_taskHost);
                    LoadMappings();

                    LoadVariables(taskHost);
                    LoadConnections();
                }
            }
        }

        private void LoadConnections()
        {
            targetCnnCombo.Items.Clear();
            foreach (ConnectionManager cn in targetPackage.Connections)
            {
                if (connectionMappingList.Items.IndexOfKey(cn.Name) == -1)
                {
                    targetCnnCombo.Items.Add(cn.Name);
                }
            }
        }

        private void LoadMappings()
        {
            varMappingList.Items.Clear();
            foreach (mappingCollection.mappingRecord mr in mappings)
            {
                if (mr.MappingType.CompareTo("Variable") == 0)
                {
                    ListViewItem lit = varMappingList.Items.Add(mr.TargetObject, mr.TargetObject, 0);
                    lit.SubItems.Add(mr.SourceObject);
                    lit.SubItems.Add(mr.MappingDirection);
                }
                
                if (mr.MappingType.CompareTo("Connection") == 0)
                {
                    ListViewItem lit = connectionMappingList.Items.Add(mr.TargetObject, mr.TargetObject, 0);
                    lit.SubItems.Add(mr.SourceObject);
                }
            }
        }

        private void ClearMappings()
        {
            mappings = new mappingCollection();
        }

        private void LoadVariables(TaskHost taskHost)
        {
            TargetVarCombo.Items.Clear();
            SourceVarCombo.Items.Clear();
            if (txtPkgPath.Text.CompareTo("") != 0)
            {
                foreach (Variable var in targetPackage.Variables)
                    {
                        if (varMappingList.Items.IndexOfKey(var.Namespace + "::" + var.Name) == -1)
                        {
                            TargetVarCombo.Items.Add(var.Namespace + "::" + var.Name);
                        }
                    }
            }
  
        }

      

        private void OKbtn_Click(object sender, EventArgs e)
        {
            try
            {
                ClearMappings();

                foreach (ListViewItem lit in varMappingList.Items)
                {
                    mappingCollection.mappingRecord mapping = new mappingCollection.mappingRecord();
                    mapping.TargetObject = lit.SubItems[0].Text;
                    mapping.SourceObject = lit.SubItems[1].Text;
                    mapping.MappingDirection = lit.SubItems[2].Text;
                    mapping.MappingType = "Variable";
                    mappings.Add(mapping);
                }

                foreach (ListViewItem cnnMapping in connectionMappingList.Items)
                {
                    mappingCollection.mappingRecord mapping = new mappingCollection.mappingRecord();
                    mapping.TargetObject = cnnMapping.SubItems[0].Text;
                    mapping.SourceObject = cnnMapping.SubItems[1].Text;
                    mapping.MappingType = "Connection";
                    mapping.MappingDirection = "Connection";
                    mappings.Add(mapping);
                }
                
                this._taskHost.Properties["PackagePath"].SetValue(_taskHost, txtPkgPath.Text);
                this._taskHost.Properties["PackageLocation"].SetValue(_taskHost, pkgLocationCombo.Text);
                this._taskHost.Properties["Mappings"].SetValue(_taskHost, mappings);
                
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Cancelbtn_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void buttonBrowse_Click(object sender, EventArgs e)
        {
            if (pkgLocationCombo.Text.CompareTo("File System") == 0)
            {
                //Browse File System
                OpenFileDialog browseFileDialog = new OpenFileDialog();
                browseFileDialog.DefaultExt = "dtsx";
                browseFileDialog.Multiselect = false;

                if (browseFileDialog.ShowDialog() == DialogResult.OK)
                {
                    //Select new file...
                    txtPkgPath.Text = browseFileDialog.FileName;

                    Microsoft.SqlServer.Dts.Runtime.Application app = new Microsoft.SqlServer.Dts.Runtime.Application();
                    targetPackage = app.LoadPackage(txtPkgPath.Text, null);

                    //ClearMappings();
                    varMappingList.Items.Clear();
                    connectionMappingList.Items.Clear();
                    LoadVariables(_taskHost);
                    LoadConnections();
                }

            }
            else //Browse SSIS Server
            {
                try
                {
                    SSISServerBrowser serverBrowser;
                    if (txtPkgPath.Text.CompareTo(string.Empty) == 0)
                    {
                        serverBrowser = new SSISServerBrowser();
                    }
                    else
                    {
                        serverBrowser = new SSISServerBrowser(txtPkgPath.Text);
                    }

                    if (serverBrowser.ShowDialog() == DialogResult.OK)
                    {
                        txtPkgPath.Text = serverBrowser.packagePath;
                        Microsoft.SqlServer.Dts.Runtime.Application app = new Microsoft.SqlServer.Dts.Runtime.Application();
                        string serverName = txtPkgPath.Text.Substring(0, txtPkgPath.Text.IndexOf("\\"));
                        string packageName = "MSDB\\" + txtPkgPath.Text.Substring(serverName.Length + 1);
                        targetPackage = app.LoadFromDtsServer(packageName,serverName , null);

                        //ClearMappings();
                        varMappingList.Items.Clear();
                        connectionMappingList.Items.Clear();
                        LoadVariables(_taskHost);
                        LoadConnections();
                    }
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.Message);
                }
            }
        }

   

        private void DeleteButton_Click(object sender, EventArgs e)
        {
            if (varMappingList.SelectedIndices.Count > 0)
            {
                varMappingList.Items.RemoveAt(varMappingList.SelectedIndices[0]);
                LoadVariables(_taskHost);
            }
        }



        private void AddButton_Click(object sender, EventArgs e)
        {
            if ((TargetVarCombo.SelectedIndex != -1) && (SourceVarCombo.SelectedIndex != -1) && (varMappingDirectionCombo.SelectedIndex != -1))
            {
                ListViewItem lit = varMappingList.Items.Add(TargetVarCombo.Text,TargetVarCombo.Text,0);
                lit.SubItems.Add(SourceVarCombo.Text);
                lit.SubItems.Add(varMappingDirectionCombo.Text);
                SourceVarCombo.Enabled = false;
                varMappingDirectionCombo.Enabled = false;
                LoadVariables(_taskHost);
            }
        }

        private void ExecPackageTaskUIForm_Load(object sender, EventArgs e)
        {

        }

        private void SourceVarCombo_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Populate Mapping direction based on read only status of selected variables
            string sourceVarName = SourceVarCombo.Text.Substring(SourceVarCombo.Text.IndexOf("::") + 2, SourceVarCombo.Text.Length - SourceVarCombo.Text.IndexOf("::") - 2);
            string targetVarName = TargetVarCombo.Text.Substring(TargetVarCombo.Text.IndexOf("::") + 2, TargetVarCombo.Text.Length - TargetVarCombo.Text.IndexOf("::") - 2);
                        
            varMappingDirectionCombo.Items.Clear();
            if (_taskHost.Variables[sourceVarName].ReadOnly == false)
            {
                varMappingDirectionCombo.Items.Add("Read");
            }
            if (targetPackage.Variables[targetVarName].ReadOnly == false)
            {
                varMappingDirectionCombo.Items.Add("Write");
            }
            if (targetPackage.Variables[targetVarName].ReadOnly == false && _taskHost.Variables[sourceVarName].ReadOnly == false)
            {
                varMappingDirectionCombo.Items.Add("Read & Write");
            }
            varMappingDirectionCombo.Enabled = true;
        }

        private void TargetVarCombo_SelectedIndexChanged(object sender, EventArgs e)
        {
            string targetVarName = TargetVarCombo.Text.Substring(TargetVarCombo.Text.IndexOf("::")+2,TargetVarCombo.Text.Length-TargetVarCombo.Text.IndexOf("::")-2);
            //Reload Variables for Source list
            SourceVarCombo.Items.Clear();
            
            foreach (Variable var in _taskHost.Variables)
            {
                if (targetPackage.Variables[targetVarName].DataType == var.DataType)
                {
                    SourceVarCombo.Items.Add(var.Namespace + "::" + var.Name);
                }
            }
            SourceVarCombo.Enabled = true;
        }

        private void targetCnnCombo_SelectedIndexChanged(object sender, EventArgs e)
        {
            sourceConnectionCombo.Items.Clear();
            foreach (ConnectionManager cn in _connections)
            {
                if (cn.CreationName.CompareTo(targetPackage.Connections[targetCnnCombo.Text].CreationName) == 0)
                {
                    sourceConnectionCombo.Items.Add(cn.Name);
                }
            }

            sourceConnectionCombo.Enabled = true;
        }

        private void addConnectionBtn_Click(object sender, EventArgs e)
        {
            if ((targetCnnCombo.SelectedIndex != -1) && (sourceConnectionCombo.SelectedIndex != -1))
            {
                ListViewItem cnnMapping = connectionMappingList.Items.Add(targetCnnCombo.Text,targetCnnCombo.Text,0);
                cnnMapping.SubItems.Add(sourceConnectionCombo.Text);
                LoadConnections();
            }
        }

        private void deleteCnnMappingBtn_Click(object sender, EventArgs e)
        {
            if (connectionMappingList.SelectedIndices.Count>0)
            {
                connectionMappingList.Items.RemoveAt(connectionMappingList.SelectedIndices[0]);
                LoadConnections();
            }
        }

        
    }
}